package top.hyz.hrm.handler;

import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.hyz.hrm.AjaxResult;
import top.hyz.hrm.exception.GlobalException;

import java.util.List;

/**
 * @ClassName GlobalExceptionHandler
 * @Description 全局异常处理
 * @Author 韩雨泽
 * @Date 2021/1/17-12:46
 * @Version 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    /**
     * 处理自定义异常
     * @param e
     * @return AjaxResult
     */
    @ExceptionHandler(GlobalException.class)
    public AjaxResult globalExceptionHandler(GlobalException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage());
    }

    /**
     * 处理系统异常
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public AjaxResult exceptionHandler(Exception e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("系统出现故障，正在殴打程序猿");
    }

    /**
     * 处理Spring框架的参数校验异常
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e){
        List<ObjectError> errorList = e.getBindingResult().getAllErrors();
        StringBuilder message = new StringBuilder();
        for (ObjectError objectError : errorList) {
            message.append(objectError.getDefaultMessage()).append(";");
        }
        return AjaxResult.me().setSuccess(false).setMessage(message.toString());
    }

}
